import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/entity/count_entity.dart';
import 'package:shopping_group/entity/widget_entity.dart';
import 'package:shopping_group/modle/login/bloc/user_auth_bloc.dart';
import 'package:shopping_group/modle/login/bloc/user_certification_bloc.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';

class UserAuthPage extends StatefulWidget {
  UserAuthPage({
    Key key,
  }) : super(key: key);
  @override
  _UserAuthPageState createState() => _UserAuthPageState();
}

class _UserAuthPageState extends State<UserAuthPage> {
  TextEditingController _controllerCode = TextEditingController();
  WidgetEntity _dtIdWidgetEntity = WidgetEntity();
  WidgetEntity _dtNameWidgetEntity = WidgetEntity();
  WidgetEntity _dtCardWidgetEntity = WidgetEntity();
  CountEntity _countEntity = CountEntity();
  UserCertificationBloc _certificationBloc;
  UserAuthBloc _bloc;
  @override
  void initState() {
    super.initState();
    _dtNameWidgetEntity = WidgetUtils.initEditText(
        '真实姓名：', '', '请输入真实姓名', 'all', TextEditingController());
    _dtIdWidgetEntity = WidgetUtils.initEditText(
        '身份证号：', '', '请输入身份证号', 'all', TextEditingController());
    _dtCardWidgetEntity = WidgetUtils.initEditText(
        '银行号：', '', '请输入银行号', 'number', TextEditingController());
    _bloc = UserAuthBloc();
    _certificationBloc = UserCertificationBloc();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: WidgetUtils.showAppar(context, '实名认证'),
        body: Container(
          height: double.infinity,
          decoration: new BoxDecoration(
            color: Colors.white,
          ),
          child: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              reverse: false,
              padding: EdgeInsets.all(0.0),
              physics: BouncingScrollPhysics(),
              child: Center(
                child: BaseConstant.isRealNameAuthen
                    ? _certifiedView()
                    : _registerBody(),
              )),
        ));
  }

  Widget _certifiedView() {
    return Container(
      margin: const EdgeInsets.only(top: 16, left: 16, right: 16),
      child: Column(
        children: <Widget>[
          FadeInImage.assetNetwork(
            image:
                'http://static.jiujiupingou.com/Static/images/real_success.png',
            placeholder: 'images/picture_loading.png',
            fit: BoxFit.cover,
          ),
          SizedBox(
            height: 16,
          ),
          WidgetUtils.getTextColorView(
            '恭喜 ${BaseConstant.name},您的身份证号：${BaseConstant.idCard.substring(0, 4)}******${BaseConstant.idCard.substring(BaseConstant.idCard.length - 4, BaseConstant.idCard.length)}认证已通过',
            Colours.green_1,
            Dimens.FONT_SIZE_16,
          ),
        ],
      ),
    );
  }

  Widget _registerBody() {
    return DefaultTextStyle(
      style: TextStyle(color: Colors.black),
      child: Container(
        margin: const EdgeInsets.only(top: 16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              height: 16,
            ),
            WidgetUtils.showEditText(_dtNameWidgetEntity),
            WidgetUtils.showEditText(_dtIdWidgetEntity),
            WidgetUtils.showEditText(_dtCardWidgetEntity),
            WidgetUtils.itmeStyleView(
              '手机号：',
              BaseConstant.code,
              bewteenleft: 16,
            ),
            WidgetUtils.drawCodeDivider(height: 1),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Container(
                    padding: const EdgeInsets.only(left: 16),
                    alignment: FractionalOffset.centerLeft,
                    child: WidgetUtils.getTextColorView(
                        '验证码：', Colours.text_2222, Dimens.FONT_SIZE_16),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: StreamBuilder(
                    stream: _certificationBloc.pushDate,
                    initialData: _countEntity,
                    builder:
                        (BuildContext context, AsyncSnapshot<Object> snapshot) {
                      Object object = snapshot.data;
                      if (object is CountEntity) {
                        _countEntity = object;
                      }
                      return Padding(
                        padding: const EdgeInsets.only(
                          left: 16,
                        ),
                        child: WidgetUtils.buildTextFieldCode(
                            _controllerCode,
                            TextInputType.phone,
                            '请输入验证码',
                            List<TextInputFormatter>()
                              ..add(LengthLimitingTextInputFormatter(18)),
                            _countEntity.codeCountdownStr,
                            Colours.blackground_609,
                            textColor: Colours.text_2222,
                            codeCallback: (callback) {
                          _usercode();
                        }),
                      );
                    },
                  ),
                ),
              ],
            ),
            WidgetUtils.drawCodeDivider(height: 1),
            SizedBox(
              height: 32,
            ),
            Container(
              alignment: Alignment.center,
              child: WidgetUtils.getTextColorView(
                '请确保信息准确，否则认证失败将无法提现',
                Colours.themeColor,
                Dimens.FONT_SIZE_16,
              ),
            ),
            SizedBox(
              height: 16,
            ),
            ButtonProgressView.crateCupertinoView('提交', cupertinoCall: () {
              _userBindName();
            }),
          ],
        ),
      ),
    );
  }

  //校验获取验证码格式
  void _usercode() {
    //  String phonename = _dtPhoneWidgetEntity.controller.text;
    // if (ObjectUtil.isEmptyString(phonename)) {
    //   BotToast.showText(text: '请输入您的手机号');
    //   return;
    // }
    // if (phonename.length != 11) {
    //   BotToast.showText(text: '请输入正确的手机号');
    //   return;
    // }

    _certificationBloc.verificationDate.add(BaseConstant.code);
  }

  void _userBindName() {
    String username = _dtNameWidgetEntity.controller.text;
    String userCard = _dtIdWidgetEntity.controller.text;
    String bankNo = _dtCardWidgetEntity.controller.text;
    String code = _controllerCode.text;
    if (ObjectUtil.isEmptyString(username)) {
      BotToast.showText(text: '请输入您的真实姓名');
      return;
    }

    if (ObjectUtil.isEmptyString(userCard)) {
      BotToast.showText(text: '请输入您的身份证');
      return;
    }

    if (ObjectUtil.isEmptyString(bankNo)) {
      BotToast.showText(text: '请输入您的银行号');
      return;
    }

    if (ObjectUtil.isEmptyString(code)) {
      BotToast.showText(text: '请输入您的验证码');
      return;
    }

    Map<String, dynamic> data = new Map<String, dynamic>();
    data['userId'] = BaseConstant.userId;
    data['name'] = username;
    data['idCard'] = userCard;
    data['phone'] = BaseConstant.code;
    data['validateCode'] = code;
    data['bankNo'] = bankNo;
    _bloc.authDate.add(data);
  }

  @override
  void dispose() {
    _dtNameWidgetEntity.controller?.clear();
    _dtIdWidgetEntity.controller?.clear();
    _dtCardWidgetEntity.controller?.clear();
    super.dispose();
  }
}
